package piwan.gui;

import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;

import piwan.*;

import javax.media.opengl.GL;

import org.fenggui.FengGUI;
import org.fenggui.Label;
import org.fenggui.util.Alignment;
import org.fenggui.util.Point;

public class WinLoseOverlay {
	private GL gl = null;
	private MainWindow win;
	private Label label = null;
	private boolean visible = false;
	private Vector2 p1 = new Vector2(), p2 = new Vector2();
	private Handler hdl = new Handler();
	private boolean hideOnEvent = false;
	
	private class Hider implements FrameListener{
		private double left;
		public Hider(double secs) {
			left = secs;
		}
		
		public void newFrame(double delta) {
			left -= delta;
			if( left<=0 ) {
				hide();
				win.removeFrameListener(this);
			}
		}
	}
	
	private class Handler extends EventHandler {
		
		public boolean onKeyPressed(KeyEvent e) {
			hide();
			return true;
		}
		
		public boolean onMousePressed(MouseEvent e) {
			hide();
			return true;
		}
	}
	
	public WinLoseOverlay( MainWindow w ) {
		this.win = w; 
		gl = w.getGL();
		label = FengGUI.createWidget(Label.class);
		label.setSize(w.getWidth()+10, 60);
		label.setPosition( new Point(0, w.getHeight()/2-label.getHeight()/2) );
		label.getAppearance().setAlignment(Alignment.MIDDLE);
		label.getAppearance().addRenderer("default", label.getAppearance().getRenderer("combatTitle"));
		label.setVisible(false);
		w.getDisplay().addWidget(label);
		widgetToWorld(p1,p2,label);
	}
	
	public void show(String msg) {
		label.setText(msg);
		label.setVisible(true);
		
		visible = true;
	}
	
	public void hide() {
		label.setVisible(false);
		visible = false;
		if(hideOnEvent) {
			win.removeEventHandler(hdl);
			hideOnEvent = false;
		}
	}
	
	public void hideAfter(double secs) {
		win.addFrameListener(new Hider(secs));
	}
	
	public void hideOnInput() { 
		hideOnEvent = true;
		win.addEventHandler(hdl);
	}
	
	public boolean isVisible() { return visible; }
	
	private void widgetToWorld(Vector2 v1, Vector2 v2, Label w) {
		v1.x = ((double)w.getX()/win.getWidth())*2.0 - 1.0;
		v2.x = ((double)(w.getX()+w.getWidth())/win.getWidth())*2.0 - 1.0;
		v1.y = ((double)w.getY()/win.getHeight())*2.0 - 1.0;
		v2.y = ((double)(w.getY()+w.getHeight())/win.getHeight())*2.0 - 1.0;
	}
	
	public void render() {
		if(visible) {
			GameGui.prepareGuiRender(gl, false);
			gl.glColor4d(0.0, 0.0, 0.0, 0.8);
			GameGui.renderRect(gl, p1, p2);
		}
	}
}
